#include "AliveCommand.h"
#include "P2PChat.h"

AliveCommand::AliveCommand()
{
	tag = new QByteArray("alive");
}

AliveCommand::~AliveCommand()
{
	delete tag;
}

/* Process the list and exec the command stuff */
void AliveCommand::executeCommand(QStringList *l, QHostAddress address) 
{
	qDebug() << "AliveCommand: " << *l;
	
	// lock the mutex.. this will be unlocked at the end of function automatically
	QMutexLocker locker(P2PChat::getInstance()->getUserMutex()); //LOCK
	
	if(l->size() != 4)
		return;
	
	/* unknow/new user? */
	if(! P2PChat::getInstance()->getUsers()->contains(l->at(1)))
	{
		User *newUser = new User(l->at(2).toUtf8(), address.toString(), l->at(3).toUtf8(), false, l->at(1).toUtf8());
		P2PChat::getInstance()->getUsers()->insert(l->at(1), newUser);
		
		//notify new User
		P2PChat::getInstance()->addConnectedUser(newUser);
		
	}
	else
	{
		//update only the 'last seen time'
		P2PChat::getInstance()->getUsers()->value(l->at(1))->updateLastSeen();
		
	}
	
}

/**
 * Getter functions
 */
QByteArray AliveCommand::getTag()
{
	return *tag;
}

QByteArray AliveCommand::getCommandDatagram()
{

	QMutexLocker locker(P2PChat::getInstance()->getUserMutex()); //LOCK

	/**
	 * Alive messages sended every timeout
	 * <ALIVE><ID><NICK><REAL_NAME>
	 */
	QByteArray aliveMsg = "<alive><" +
									*(P2PChat::getInstance()->getMySelf()->getID()) +
									"><" + 
									*(P2PChat::getInstance()->getMySelf()->getNick()) +
									">" +
									"<" + 
									*(P2PChat::getInstance()->getMySelf()->getRealName()) +
									">";
	
	return aliveMsg;
}
